/**
 *  Copyright 2002-2009 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package foo.bar.forum.web.extension;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.controller.FileUploadLimitExceededException;
import net.sourceforge.stripes.exception.DefaultExceptionHandler;
import net.sourceforge.stripes.exception.ExceptionHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Serializable;
import java.util.Map;
import java.util.HashMap;

import foo.bar.forum.web.action.general.FileUploadLimitExceededActionBean;
import foo.bar.forum.web.action.general.UncaughtExceptionActionBean;

/**
 * A custom excetpion handler that keeps the following information in the current http request attribute :-
 *
 * <ul>
 *  <li>stackTrace - the stack trace of the exception (in string)</li>
 * </ul>
 *
 * If it's a {@link net.sourceforge.stripes.controller.FileUploadLimitExceededException}, the following
 * extra http requst attributes are also available :-
 * <ul>
 *  <li>postedSize - the size of the attachment </li>
 *  <li>maxSize - the max size of attachment allowed</li>
 * </ul>
 *
 *
 * @author tmjee
 * @version $Date$ $Id$
 */
public class CustomExceptionHandler extends DefaultExceptionHandler {

    private static final Log LOG = LogFactory.getLog(CustomExceptionHandler.class);

        private Configuration configuration;

        public void init(Configuration configuration) throws Exception {
            this.configuration = configuration;
            super.init(configuration);
        }
    

        /**
         * Handle {@link net.sourceforge.stripes.controller.FileUploadLimitExceededException}.
         *
         * @param e
         * @param request
         * @param response
         * @return
         */
        public Resolution handleFileUploadLimitExceededException(final FileUploadLimitExceededException e,
                                                                 final HttpServletRequest request,
                                                                 final HttpServletResponse response) {
            LOG.error(e.toString(), e);
            HttpSession session = request.getSession(true);
            session.setAttribute("__stackTrace", stackTraceAsString(e));
            session.setAttribute("__postedSize", e.getPosted());
            session.setAttribute("__maxSize", e.getMaximum());
            return new RedirectResolution(FileUploadLimitExceededActionBean.class, "view");
        }


        /**
         * Handle all other exception.
         *
         * @param t
         * @param request
         * @param response
         * @return
         */
        public Resolution handleUncaughtedException(final Throwable t,
                                                    final HttpServletRequest request,
                                                    final HttpServletResponse response) {
            LOG.error(t.toString(), t);
            HttpSession session = request.getSession(true);
            session.setAttribute("__stackTrace", stackTraceAsString(t));
            return new RedirectResolution(UncaughtExceptionActionBean.class, "view");
        }



        protected String stackTraceAsString(Throwable t) {
            StringWriter _writer = null;
            PrintWriter writer = null;
            try {
                _writer = new StringWriter();
                writer = new PrintWriter(_writer);
                t.printStackTrace(writer);
                return _writer.getBuffer().toString();
            }
            finally {
                if (_writer != null) {
                    try {
                        _writer.close();
                    } catch (IOException e) {
                    }
                }
                if (writer != null) {
                    writer.close();
                }
            }
        }
}
